import {AxiosRequestHeaders} from "axios";
import HttpClient from "./http-client.js";
import {MockerStyle, RequestConfig} from "./http-client-type.js";
import HttpClientUtil from "./http-client-util.js";

/**
 * 请求成功拦截器。不能使用箭头函数，否则无this
 * @param requestConfig
 */
const handleRequestFulfilled = function handleRequestFulfilled(
    this: HttpClient,
    requestConfig: RequestConfig<any>
) {
  // log.debug("requestConfig：{}", requestConfig);

  // loading
  if (
      typeof requestConfig.showLoading === "function"
          ? requestConfig.showLoading()
          : requestConfig.showLoading
  ) {
    requestConfig.showLoadingFunction();
  }

  // header
  requestConfig.beforeHandleRequestHeaders.bind(this)(requestConfig);
  requestConfig.handleRequestHeaders(
      requestConfig.headers as AxiosRequestHeaders
  );
  requestConfig.afterHandleRequestHeaders(requestConfig);

  // mock
  if (!HttpClientUtil.isMocked(requestConfig, this.mockConfig)) {
    return requestConfig;
  }

  if (
      HttpClientUtil.mockStyle(requestConfig, this.mockConfig) ===
      MockerStyle.SERVER
  ) {
    const mockServerBaseUrl = HttpClientUtil.mockServerBaseUrl(
        requestConfig,
        this.mockConfig,
    );
    requestConfig.url = mockServerBaseUrl + requestConfig.url;
    return requestConfig;
  }

  return requestConfig;
};

export default handleRequestFulfilled;
